package m.store.action;

import m.appserver.AuthInfoUtil;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.store.model.IncomeAmount;
import m.store.model.IncomeAmountRecord;
import m.store.model.OrderModel;
import m.store.model.IncomeAmountRecord;
import m.store.service.IncomeAmountService;
import m.store.service.StoreNumberService;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "store/incomeAmount")
public class IncomeAmountAction extends OrderModelAction {
    private IncomeAmount model;
    private List<IncomeAmountRecord> saleList;

    /**
     * 保存
     */
    @RequestMeta(transaction = true,logTitle = "收款信息",logDescription = "保存收款信息")
    public JSONMessage doSave() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        String msg=getService(IncomeAmountService.class).save(model,saleList);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    @RequestMeta(transaction = true,logTitle = "收款信息",logDescription = "保存并提交收款信息")
    public JSONMessage doSaveAndSubmit() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        getService(IncomeAmountService.class).saveAndSubmit(model,saleList);
        return new JSONMessage(0,"提交成功");
    }
    @RequestMeta(transaction = true,logTitle = "收款信息",logDescription = "删除收款信息")
    public JSONMessage doDelete() throws Exception {
        getService(IncomeAmountService.class).delete(model.getOid(),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"删除成功");
    }
    @RequestMeta(transaction = true,logTitle = "收款信息",logDescription = "审核通过收款信息")
    public JSONMessage doCheck() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Finance);
        getService(IncomeAmountService.class).check(model.getOid(),model.getIncomeDate(),model.getRemark(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"审核成功");
    }
    @RequestMeta(transaction = true,logTitle = "收款信息",logDescription = "提交收款信息")
    public JSONMessage doRefund() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Finance);
        getService(IncomeAmountService.class).refund(model.getOid(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"退回成功");
    }
    /*
     * 编辑收款
     */
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            saleList=ModelQueryList.getModelList(IncomeAmountRecord.class,new String[]{"*","sale.*"},null,
                    QueryCondition.eq("income.oid",model.getOid()));
        }else{
            model=new IncomeAmount();
            model.setOrderNo(StoreNumberService.getNextIncomeNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setIncomeDate(new Date());
            saleList=new ArrayList<>();
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Finance);

        ModelForm form = new ModelForm("出库收款信息");
        form.addItem(
            FormHtml.inputStyle("收款单号","{{model.orderNo}}"),
            FormInput.selectOneModel("付款客户", "model","guest","'action/store/guestInfo/selectOneGuest'",1300,"<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2).setEdit(edit),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("收款金额","<b>{{formatNumber(model.incomeAmount,'#,##0.00')}}</b>"),
            FormInput.date("收款日期","model.incomeDate").setEdit(edit||check).setRequired(true),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model)
        .addWatch("model.guest.oid","this.saleList=[];")
        .addButton(
            edit? FormButton.pri("保存","doSave"):null,
            edit?FormButton.succ("提交","doSaveAndSubmit").setConfirm("确定要提交吗？"):null,
            check?getCheckFormButton(model.getOid()):null,
            check?FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,saleList:this.saleList}")
                .fillData("model"),
            FormEvent.doJson("doSaveAndSubmit",actionUrl("doSaveAndSubmit"),"{model:this.model,saleList:this.saleList}")
                .success("backFlag"),
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("出库订单").setEdit(edit,true,"{sale:{}}",false);
        form1.setData("saleList",saleList)
        .addMethod(
            FormEvent.custom("editDataAfter",
                "var sum=0.0;" +
                "for(var i=0;i<this.saleList.length;i++){" +
                " sum+=(this.saleList[i].incomeAmount||0);" +
                "}" +
                "this.model.incomeAmount=sum;"
            )
        )
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("出库单号","sale.orderNo",130)
                .setEdit(TableEdit.selectOneModel("'action/store/saleInfo/selectOneChecked?params[guest.oid]='+model.guest.oid",900,"sale","orderNo")),
            TableColumn.center("出库日期","stock.saleDate",100).setDateFormat("yyyy-MM-dd")
                .setEdit(Element.tag("div").E("{{formatDate(editRecord.sale.saleDate,'yyyy-MM-dd')}}")),
            TableColumn.number("出库金额","sale.saleAmount",90).isSum(false)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.sale.saleAmount,'#,##0.00')}}")),
            TableColumn.number("尚欠金额","sale.oweAmount",90)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.sale.oweAmount,'#,##0.00')}}")),
            TableColumn.number("收款金额","incomeAmount")
                .setEdit(TableEdit.number()),
            TableColumn.text("备注","remark")
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    public VueResult toView() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.name","inputUser.realname","checkUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
        }else{
            throw AuthInfoUtil.noPowerException;
        }
        ModelForm form = new ModelForm("出库收款信息");
        form.addItem(
            FormHtml.inputStyle("收款单号", "{{model.orderNo}} {{dict('m.store.model.IncomeAmount!status',model.status)}}"),
            FormHtml.inputStyle("登记人", "{{model.inputUser.realname}} {{formatDate(model.submitDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("审核人", "{{model.checkUser.realname}} {{formatDate(model.checkDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("收款日期","{{formatDate(model.incomeDate,'yyyy-MM-dd')}}"),
            FormHtml.inputStyle("付款客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle("收款金额", "<b>{{formatNumber(model.incomeAmount,'#,##0.00')}}</b>"),
            FormHtml.inputStyle("备注","{{model.remark}}").setSpan(3)
        )
        .addData("model",model)
        .addMethod(
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        LoadPage recordPage=new LoadPage("loadRecordPage",actionUrl(IncomeAmountRecordAction.class,"recordList"),"{params:{'income.oid':this.model.oid}}")
                .setMounted("this.loadRecordPage();");
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(recordPage);
    }
    /*
     * 我的收款列表
     */
    public VueResult myInputList() throws Exception {
        VueListResult result=getVueListResult("我的出库收款登记",IncomeAmount.class,actionUrl("myInputList"));
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("收款单号", "orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("付款客户", "guest.name", 100, true));
        result.addCol(toNumberColumn("收款金额", "incomeAmount", 100, true));
        result.addCol(toDateColumn("收款时间", "incomeDate", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.addCol(toSpaceColumn("操作", 140,
            ListElement.test("record.status=='"+ OrderModel.Status_Register+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'",
                ListButton.ajax("删除", ButtonType.ERROR,actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid").setConfirm("确定要删除吗？")
            )
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.page("登记收款", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
        );
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("收款单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款时间","incomeDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUser(true).getOid()));
        return result;
    }
    /*
     * 待审核列表
     */
    public VueResult checkList() throws Exception {
        VueListResult result=getVueListResult("出库收款待审核",IncomeAmount.class,actionUrl("checkList"));
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("收款单号", "orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("付款客户", "guest.name", 100, true));
        result.addCol(toNumberColumn("收款金额", "incomeAmount", 100, true));
        result.addCol(toDateColumn("收款时间", "incomeDate", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        fillOrderColumn(result);
        if(PowerUtil.hasPower(PowerUtil.Finance)) {
            result.addCol(toSpaceColumn("操作", 100,
                ListButton.page("审核", ButtonType.PRIMARY, actionUrl("toEdit"),  SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid")
            ).setFixed(Align.RIGHT));
        }
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("收款单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款时间","incomeDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("status",OrderModel.Status_Check));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }

    public VueResult queryList() throws Exception {
        VueListResult result=getVueListResult("出库收款账单",IncomeAmount.class,actionUrl("queryList"));
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("收款单号", "orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("付款客户", "guest.name", 100, true));
        result.addCol(toNumberColumn("收款金额", "incomeAmount", 100, true));
        result.addCol(toDateColumn("收款时间", "incomeDate", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("收款单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款时间","incomeDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }
    /*
     * 订单收款台账列表
     */
    public VueResult orderIncomeQuery() throws Exception {
        VueListResult result=getVueListResult("订单收款台账", IncomeAmountRecord.class,actionUrl("orderIncomeQuery"));
        result.addCol(toIndexColumn());
        result.addCol(toNumberColumn("本次收款金额", "incomeAmount", 120, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toLinkColumn("收款单号", "income.orderNo", 100, true,
                new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                        .addParam("model.oid","income.oid")
        ));
        result.addCol(toTextColumn("客户名称", "income.guest.name", 150, true));
        result.addCol(toDateColumn("收款时间", "income.incomeDate", 100, true));
        result.addCol(toNumberColumn("收款金额", "income.incomeAmount", 100, true).setCount(ListCount.NONE));
        result.addCol(getStatusColumn("income.status"));
        result.addCol(toTextColumn("登记人", "income.inputUser.realname", 100, true));
        result.addCol(toDateColumn("录入时间", "income.inputDate", 100, true));
        result.addCol(toTextColumn("审核人", "income.checkUser.realname", 100, true));
        result.addCol(toDateColumn("审核时间", "income.checkDate", 100, true));
        result.addCol(toTextColumn("类型", "sale.type", 100, true).setDictType("m.store.model.SaleInfo!type"));
        result.addCol(toLinkColumn("出库单号", "sale.orderNo", 100, true,
                new ListEvent(actionUrl(SaleInfoAction.class,"toView"), EventType.MODAL,1200)
                        .addParam("model.oid","sale.oid")
        ));
        result.addCol(toDateColumn("出库日期", "sale.saleDate", 100, true));
        result.addCol(toNumberColumn("出库金额", "sale.saleAmount", 100, true).setCount(ListCount.NONE));
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("收款单号","income.orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("客户名称","income.guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款时间","income.incomeDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("income.store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }
    public List<IncomeAmountRecord> getSaleList() {
        return saleList;
    }

    public void setSaleList(List<IncomeAmountRecord> saleList) {
        this.saleList = saleList;
    }

    public IncomeAmount getModel() {
        return model;
    }

    public void setModel(IncomeAmount model) {
        this.model = model;
    }
}
